package com.hefan.notify.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.hefan.notify.bean.PubParams;
import com.hefan.notify.bean.WebPushParam;
import com.hefan.notify.itf.UmengPushService;
import com.hefan.notify.itf.WebUmengPushService;
import com.hefan.user.itf.LoginTokenService;

@Path("/webPush")
@Component("webUmengPushService")
public class WebUmengPushServiceImpl implements WebUmengPushService{
	
	Logger logger = LoggerFactory.getLogger(WebUmengPushServiceImpl.class);
	
	@Resource
    LoginTokenService loginTokenService;
	@Resource
	UmengPushService umengPushService;

	@POST
	@Path("/webPushByParams")
	@Produces({ MediaType.APPLICATION_JSON })
	@Consumes({ MediaType.APPLICATION_JSON })
	@Override
	public ResultBean webPushByParams(@RequestBody WebPushParam webPushParam) {
		// TODO Auto-generated method stub
		ResultBean res = new ResultBean(ResultCode.SUCCESS.get_code(),"推送成功");
		logger.info("webPushByParams推送信息"+JSON.toJSONString(webPushParam));
		try {
			//校验
			if(webPushParam == null){
				res.setCode(ResultCode.UNSUCCESS.get_code());
				res.setMsg("未接收到参数");
				return res;
			}
			if(StringUtils.isBlank(webPushParam.getContent())){
				res.setCode(ResultCode.UNSUCCESS.get_code());
				res.setMsg("推送内容不能为空");
				return res;
			}
			if(StringUtils.isBlank(webPushParam.getTitle())){
				res.setCode(ResultCode.UNSUCCESS.get_code());
				res.setMsg("推送标题不能为空");
				return res;
			}
			 //0:所有用户 1:所有主播（网红）  2:所有明星（明星/片场）  3:个人（指定的多个人） 4:所有普通用户
			switch (webPushParam.getUserType()) {
			case 0:
				//所有人
				res=this.webPushAll(webPushParam);
				break;
			case 1:
				//所有主播（网红）
				res=this.webPushUserByUserType(webPushParam);
				break;
			case 2:
				//所有明星（明星/片场）
				res=this.webPushUserByUserType(webPushParam);
				break;
			case 3:
				//个人（指定的多个人）
				res=this.webPushUserByUserType(webPushParam);
				break;
			case 4:
				//所有普通用户
				res=this.webPushUserByUserType(webPushParam);
				break;
			default:
				res.setCode(ResultCode.UNSUCCESS.get_code());
				res.setMsg("接收人类型出错");
				break;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info("webPushByParams推送失败："+e.getMessage());
		}
		logger.info("webPushByParams推送返回："+JSON.toJSONString(res));
		return res;
	}
	
	private ResultBean webPushAll(WebPushParam webPushParam){
		ResultBean res = new ResultBean(ResultCode.SUCCESS.get_code(),"推送成功");
		PubParams param = new PubParams();
		param.setTicker(webPushParam.getTitle());
		param.setTitle(webPushParam.getTitle());
		param.setText(webPushParam.getContent());
		boolean rs = umengPushService.sendBroadcast(param);
		if(!rs){
			res.setCode(ResultCode.UNSUCCESS.get_code());
			res.setMsg("推送失败");
		}
		return res;
	}
	
	private ResultBean webPushUserByUserType(WebPushParam webPushParam){
		ResultBean res = new ResultBean(ResultCode.SUCCESS.get_code(),"推送成功");
		PubParams param = new PubParams();
		param.setTicker(webPushParam.getTitle());
		param.setTitle(webPushParam.getTitle());
		param.setText(webPushParam.getContent());
		try {
			List<String> list = new ArrayList<String>();
			if(webPushParam.getUserType() == 1){
				list = this.loginTokenService.getUserByUserType(new String [] {"1"});
			}else if(webPushParam.getUserType() == 2){
				list = this.loginTokenService.getUserByUserType(new String [] {"2","3"});
			}else if(webPushParam.getUserType() == 3){
				list = webPushParam.getUserId();
			}else if(webPushParam.getUserType() == 4){
				list = this.loginTokenService.getUserByUserType(new String [] {"0"});
			}
			if(list == null || list.size()<0){
				res.setCode(ResultCode.UNSUCCESS.get_code());
				res.setMsg("没有找到可推送的设备");
				return res;
			}
			if(list.size()< 50){
				//列播
				StringBuilder devS = new StringBuilder("");
				for(int i =0;i<list.size();i++){
					devS.append(list.get(i));
					if(i<list.size()-1){
						devS.append(",");
					}
				}
				param.setDeviceTokens(devS.toString());
				boolean rs = umengPushService.sendCustomizedcast(param);
				if(!rs){
					res.setCode(ResultCode.UNSUCCESS.get_code());
					res.setMsg("推送失败");
				}
				return res;
			}else{
				//文件播
				//上传文件
				StringBuffer contentBuffer = new StringBuffer();
				for (String deviceTokens: list) {
					if(StringUtils.isBlank(deviceTokens)){
						continue;
					}
				    contentBuffer.append(deviceTokens);
				    contentBuffer.append("\n"); // don't forget the return character
				}
				if(StringUtils.isBlank(contentBuffer.toString())){
					res.setCode(ResultCode.UNSUCCESS.get_code());
					res.setMsg("未找到要推送的设备");
					return res;
				}
				//and
				try {
					String fileIdAND = this.umengPushService.upLoadTokenFile(contentBuffer.toString(), 1);
					if(StringUtils.isNotBlank(fileIdAND)){
						param.setFileId(fileIdAND);
						this.umengPushService.sendAndroidCustomizedcast(param);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.error("开播提醒AND文件上传失败");
					e.printStackTrace();
				}
				//ios
				try {
					String fileIdIOS = this.umengPushService.upLoadTokenFile(contentBuffer.toString(), 2);
					if(StringUtils.isNotBlank(fileIdIOS)){
						param.setFileId(fileIdIOS);
						this.umengPushService.sendIOSCustomizedcast(param);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.error("开播提醒IOS文件上传失败");
					e.printStackTrace();
				}
				return res;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res.setCode(ResultCode.UNSUCCESS.get_code());
			res.setMsg("推送失败");
			return res;
		}
	}

}
